package com.rules.admin.service.impl;



import com.rules.admin.domain.SysResourceRelation;
import com.rules.admin.domain.SysResource;
import com.rules.admin.service.ResourceService;
import com.rules.admin.utils.ResourceUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.util.List;
import java.util.Map;

@Service("resourceService")
public class ResourceServiceImpl implements ResourceService, InitializingBean {
   @Autowired
   private DataSource dataSource;
   private JdbcTemplate jdbcTemplate;

   public Map<AntPathRequestMatcher, SysResource> loadAllUrlMatcherWithResource() {
      List<SysResource> resources = this.jdbcTemplate.query("SELECT RESOURCE_ID, URL  FROM rul_sys_resource", BeanPropertyRowMapper.newInstance(SysResource.class));
      List<SysResourceRelation> resourceRelations = this.jdbcTemplate.query("SELECT RESOURCE_ID, PARENT_RESOURCE_ID FROM rul_SYS_RESOURCE_REL", BeanPropertyRowMapper.newInstance(SysResourceRelation.class));
      return ResourceUtils.buildResourceData(resources, resourceRelations);
   }

   public void afterPropertiesSet() {
      this.jdbcTemplate = new JdbcTemplate(this.dataSource);
   }
}
